package router

import (
	"github.com/golang/glog"
	_ "github.com/go-sql-driver/mysql"
	"sync"
	"cloud_worm/util/proto/ujson"
	"cloud_worm/util/umodels/mysqldb/dbmanager"
	"cloud_worm/util/umodels/mysqldb"
	"time"
)

type RouteMap struct {
	ServerConfig 	map[string]ujson.AgentRouteConfig
	mux 			sync.Mutex
}

func (d *RouteMap) SelectAllRouterInfo() (map[string]ujson.AgentRouteConfig, error) {
	routeConfigs := make(map[string]ujson.AgentRouteConfig)

	rc := &dbmanager.RouterConfig{}
	rcs, err := rc.SelectWithStatus(mysqldb.SelectOffsetZero, mysqldb.SelectLimitAll, mysqldb.StatusValid)
	if err != nil {
		//glog.Error("db Query error: ", err.Error())
		return routeConfigs, err
	}

	var routeInfo ujson.AgentRouteConfig
	for _, item := range rcs {
		routeInfo.ConfigUrl = item.ConfigUrl
		routeInfo.SocketAddress = item.ServerAddress
		routeInfo.Timeout = item.IntervalTime
		routeInfo.HeartbeatTimeout = item.HeartbeatTimeout

		routeConfigs[item.Version] = routeInfo
	}

	return routeConfigs, nil
}

func (d *RouteMap) LoadConfigLoop(wg *sync.WaitGroup)  {

	go func(wg *sync.WaitGroup) {
		wg.Add(1)
		glog.Infof("start load config loop.")
		for {
			configs, err := d.SelectAllRouterInfo()
			if err != nil {
				//glog.Errorf("select all router config error: %s", err.Error())
				time.Sleep(60 * time.Second)
				continue
			}

			d.mux.Lock()
			d.ServerConfig = configs
			d.mux.Unlock()

			time.Sleep(30 * time.Second)
		}

		wg.Done()
		return
	}(wg)

	return
}

var RouteSrvMap = &RouteMap{
	ServerConfig: make(map[string]ujson.AgentRouteConfig),
}